package com.lxw.filesystem.service;

import com.lxw.filesystem.dao.FilesSystemDao;
import com.lxw.framework.domain.filesystem.FileSystem;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileServiceImpl implements  IFileService  {
    @Value("${fastdfs.tracker_servers}")
    String tracker_servers;
    @Value("${fastdfs.connect_timeout_in_seconds}")
    int connect_timeout_in_seconds;
    @Value("${fastdfs.network_timeout_in_seconds}")
    int network_timeout_in_seconds;
    @Value("${fastdfs.charset}")
    String charset;

    @Autowired
    FilesSystemDao filesSystemDao;

    //加载fdfs的配置
    private void initFdfsConfig() {
        try {
            ClientGlobal.initByTrackers(tracker_servers);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
            ClientGlobal.setG_charset(charset);
        } catch (Exception e) {
            e.printStackTrace();
            //初始化文件系统出错
        }
    }


    @Override
    public FileSystem upload(MultipartFile multipartFile, String filetag, String businesskey, String metadata) {
        initFdfsConfig();

        try {
            String originalFilename = multipartFile.getOriginalFilename();
           String extName =  originalFilename.substring(originalFilename.lastIndexOf(".")+1);//+1原因是要把.去掉

            // 1.tracker
            TrackerClient trackerClient = new TrackerClient();
            //获取trackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            System.out.println(trackerServer.getInetSocketAddress());

            // 2.storageServer
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            System.out.println(storageServer.getInetSocketAddress());

            // 3.上传
            StorageClient1 storageClient1 = new StorageClient1(trackerServer,storageServer);
//            String fileName = "C:\\Users\\Administrator\\Pictures\\20210131203506.png";
            byte[] bytes = multipartFile.getBytes();


            String fileId = storageClient1.upload_file1(bytes, extName, null);
            System.out.println(fileId);

            FileSystem fileSystem = new FileSystem();
            fileSystem.setFileId(fileId);
            fileSystem.setFilePath(fileId);
            fileSystem.setFileName(originalFilename);
            fileSystem.setFileType(multipartFile.getContentType());
            fileSystem.setFiletag(filetag);
            fileSystem.setFileSize(multipartFile.getSize());
            return filesSystemDao.save(fileSystem);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }
}
